package com.huahua.bigdata.spark.rdd.operate;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class Spark11_Operate_Transform_KV_wordCount {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf();
        conf.setMaster("local");
        conf.setAppName("spark");
        JavaSparkContext jsc = new JavaSparkContext(conf);
        JavaPairRDD<String, Integer> pairRDD = jsc.parallelizePairs(
                Arrays.asList(
                        new Tuple2<>("a", 1),
                        new Tuple2<>("b", 2),
                        new Tuple2<>("a", 3),
                        new Tuple2<>("b", 4)
                )
        );
        JavaPairRDD<String, Integer> wordCountRDD = pairRDD.groupByKey().mapValues(
                iter -> {
                    int sum = 0;
                    Iterator<Integer> iterator = iter.iterator();
                    while (iterator.hasNext()) {
                        Integer num = iterator.next();
                        sum = sum + num;
                    }
                    return sum;
                }
        );
        wordCountRDD.collect().forEach(System.out::println);

        jsc.close();
    }
}
